package cn.tedu.springmvc.controller;

import cn.tedu.springmvc.dto.UserRegDTO;
import cn.tedu.springmvc.vo.UserVO;
import cn.tedu.springmvc.web.JsonResult;
import cn.tedu.springmvc.web.State;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/users")
public class UserController {

    public UserController() {
        System.out.println("UserController.UserController()");
    }



    // 注意：以下URL中，spring_mvc_war_exploded这个部分，各项目可能不同
    // http://localhost:8080/spring_mvc_war_exploded/user/hello.do
    // @RequestMapping可用于配置【请求路径】与【处理请求的方法】的映射关系
    // @ResponseBody用于将方法的返回值以【响应正文】的方式响应到客户端
    // 注意：在Spring MVC框架中，默认，响应的字符串正文并不支持中文
    // @RequestMapping(value = "/hello.do", method = RequestMethod.GET)
    @GetMapping("/hello.do") // HandlerMapping
    public JsonResult sayHello(String username) {
        int l = username.length();
        return JsonResult.ok("username length = " + l);
    }

    // maven-webapp-tomcat >> http://localhost:8080/maven_webapp_tomcat_war_exploded
    // http://localhost:8080/spring_mvc_war_exploded/user/login.do
    // Content-Type
    @RequestMapping("/login.do")
    public JsonResult login(String username, String password) {
        // 假设root/1234是正确的账号
        if ("root".equals(username)) {
            if ("1234".equals(password)) {
                return JsonResult.ok();
            } else {
                return JsonResult.fail(State.ERR_PASSWORD, "登录失败，密码错误！");
            }
        } else {
            return JsonResult.fail(State.ERR_USERNAME, "登录失败，用户名错误！");
        }
    }

    // http://localhost:8080/spring_mvc_war_exploded/user/reg.do
    @RequestMapping("/reg.do")
    public JsonResult reg(UserRegDTO userRegDTO) {
        System.out.println("userRegDTO = " + userRegDTO);
        return null;
    }

    @GetMapping("/info.do")
    public JsonResult<UserVO> info() {
        UserVO user = new UserVO();
        user.setUsername("chengheng");
        user.setPassword("1234567890");
        user.setEmail("chengheng@qq.com");

//        JsonResult jsonResult = new JsonResult();
//        jsonResult.setState(1);
//        jsonResult.setData(user);
//
//        return jsonResult;
        // return new JsonResult(2, "用户数据不存在！");
        // return new JsonResult(1, user);
        return JsonResult.ok(user);
    }

    // http://localhost:8080/xxxx/users/9527/info.do
    // http://localhost:8080/xxxx/users/9999/info.do?username=root
    @GetMapping("/{id:[0-9]+}/info.do")
    public JsonResult getInfoById(@PathVariable Long id) {
        return null;
    }

    // http://localhost:8080/xxxx/users/xyz/info.do
    @GetMapping("/{username:[a-zA-Z]+}/info.do")
    public JsonResult getInfoByUsername(@PathVariable String username) {
        return null;
    }

    // http://localhost:8080/xxxx/users/list/info.do
    @GetMapping("/list/info.do")
    public JsonResult getListInfo() {
        return null;
    }

}
